package org.swqsbssddqs.shortlink.project.mq.idempotent;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
@Slf4j
public class MessageQueueIdempotentHandler {
    private static final String IDEMPOTENT_KEY_PREFIX = "short-link:idempotent:";
    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 判断当前消息是否消费过
     *
     * @param messageId 消息唯一标识
     * @return 消息是否消费过
     */
    public boolean isMessageBeingConsumed(String messageId) {
        String key = IDEMPOTENT_KEY_PREFIX + messageId;
        return Boolean.FALSE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key, "0", 60, TimeUnit.MINUTES));
    }

    public boolean delMessage(String messageId) {
        String key = IDEMPOTENT_KEY_PREFIX + messageId;
        return stringRedisTemplate.delete(key);
    }
    public boolean isAccomplish(String messageId) {
        String key = IDEMPOTENT_KEY_PREFIX + messageId;
        return Objects.equals(stringRedisTemplate.opsForValue().get(key),"1");
    }
    public void setAccomplish(String messageId) {
        String key = IDEMPOTENT_KEY_PREFIX + messageId;
        stringRedisTemplate.opsForValue().set(key, "1", 60, TimeUnit.MINUTES);
    }

}
